package com.tbrain.secretFriend.service;
import java.sql.*;
import java.util.*;

import com.tbrain.secretFriend.model.User;
import com.tbrain.secretFriend.model.Wish;

public class WishService {
	private Connection conn;

	public WishService(Connection c){
		conn = c;
	}

	public List selectWishList(User user){
		List list = new ArrayList();
		PreparedStatement p;
		try {
			p = conn.prepareStatement("SELECT WishId,Description,Comments,UserId FROM SF_WISH WHERE UserId = ? ORDER BY WishId");
			p.setInt(1, user.getUserId());
			ResultSet r = p.executeQuery();
			while(r.next()){
				Wish wish = new Wish();
				wish.setWishId(r.getInt(1));
				wish.setDescription(r.getString(2));
				wish.setComments(r.getString(3));
				wish.setUserId(r.getInt(4));
				list.add(wish);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return list;
	}

	public void deleteWishList(User user){
		PreparedStatement p;

		System.out.println("entra al delete");
		try {
			p = conn.prepareStatement("DELETE FROM SF_WISH WHERE UserId = ?");
			p.setInt(1, user.getUserId());
			p.execute();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public int getNextWishId(){
		int nextId=1;
		try {
			PreparedStatement p = conn.prepareStatement("SELECT MAX(WishId) FROM SF_WISH");
			ResultSet r = p.executeQuery();
			if(r.next()){
				nextId = r.getInt(1);
				nextId++;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return nextId;
	}

	public boolean insert(Wish wish){
		try{
			if(wish.getWishId()==0){
				wish.setWishId(getNextWishId());
			}
			PreparedStatement p = conn.prepareStatement("INSERT INTO SF_WISH (WishId,Description,Comments,UserId) VALUES ( ?,?,?,? )");
			p.setInt(1, wish.getWishId());
			p.setString(2, wish.getDescription());
			p.setString(3, wish.getComments());
			p.setInt(4, wish.getUserId());
			int value = p.executeUpdate();
			if(value>0){
				return true;
			}
		}catch(SQLException e){
			e.printStackTrace();
		}
		return false;
	}

}

